package com.cwj.algorithm.sort;

import java.util.List;

/**
 * @author chenwujie
 * @date 2020/11/0915:36
 */
public class BubbleSort {

    public static <T extends Comparable<? super T>> void sort(List<T> data){
        for (int i = 0; i < data.size() - 1; i++) {
            for (int j = i + 1; j < data.size(); j++) {
                if(greater(data.get(i), data.get(j))){
                    exchange(data, i, j);
                }
            }
        }
    }

    public static <T extends Comparable<? super T>> void sort(T[] data){
        for (int i = 0; i < data.length - 1; i++) {
            for (int j = i + 1; j < data.length; j++) {
                if(greater(data[i], data[j])){
                    exchange(data, i, j);
                }
            }
        }
    }

    private static <T extends Comparable<? super T>> boolean greater(T a, T b){
        return a.compareTo(b) > 0;
    }
    private static <T extends Comparable<? super T>> void exchange(List<T> data, int i, int j){
        T temp = data.get(i);
        data.set(i, data.get(j));
        data.set(j, temp);
    }

    private static <T extends Comparable<? super T>> void exchange(T[] data, int i, int j){
        T temp = data[i];
        data[i] = data[j];
        data[j] = temp;
    }
}
